if minetest.setting_getbool("gohome_eatdust")~=true then
	minetest.setting_set("gohome_eatdust","false")
end

lunomods.on_newplayer = function(player)
	if player ~= nil and player:is_player() then
		local name = player:get_player_name()
		--print("[lunomods/on_command_respawnall.lua >>>> lunomods.on_newplayer(player='"..name.."')]")
		local toPos = lunomods.getGlobalValue("posRespawnAll")
		if toPos~=nil then
			--print("[lunomods/on_command_respawnall.lua  >>>> lunomods.on_newplayer(player='"..name.."')] toPos = "..toPos)
			if toPos~=nil and type(toPos)=="table" and toPos~="" then
				--minetest.chat_send_all("Novo jogador '"..name.."' nasceu em '"..minetest.pos_to_string(toPos).."'...")
				minetest.chat_send_all("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
				player:setpos(minetest.string_to_pos(toPos)) --Favor nao por som antes do player ser instaciado no servidor
				minetest.chat_send_all("Novo jogador '"..name.."' nasceu em '"..toPos.."'...")
				return true --Tem q dar retorno ou nao vai funcionar.
			else
				print("[lunomods/on_command_respawnall.lua >>>> lunomods.on_newplayer(player='"..name.."')] toPos='"..dump(toPos).."'")
			end
		end
	else
		print("[lunomods/on_command_respawnall.lua >>>> lunomods.on_newplayer(player='???????')] Erro => Variavel 'player' nao foi declarada.")
	end
end

lunomods.on_respawnplayer = function(player)
	if player ~= nil and player:is_player() then
		local name = player:get_player_name()
		--print("[lunomods/on_command_respawnall.lua ==> (lunomods.on_respawnplayer(player='"..name.."'))]")
		local posRespawn = lunomods.getCharValue(name, "posRespawn")
		local posRespawnAll = lunomods.getGlobalValue("posRespawnAll")
		if posRespawn~=nil and posRespawn~="" then
			minetest.chat_send_all(name.." renasceu no carpete em '"..posRespawn.."'.")
			player:setpos(minetest.string_to_pos(posRespawn)) --Favor nao por som antes do player ser instaciado no servidor
			return true
		elseif posRespawnAll~=nil and posRespawnAll~="" then
			minetest.chat_send_all(name.." renasceu no respawn principal.")
			player:setpos(minetest.string_to_pos(posRespawnAll)) --Favor nao por som antes do player ser instaciado no servidor
			return true
		else
			local newpos = {
				x = math.random(-1000,1000),
				y = 0,
				z = math.random(-1000,1000)
			}
			--for _, player in ipairs(minetest.get_connected_players()) do
			repeat
				newpos.y = newpos.y + 1
				local nodename1 = minetest.env:get_node(newpos).name
				local nodename2 = minetest.env:get_node({x=newpos.x,y=newpos.y+1,z=newpos.z}).name
				--print("############################# C"..minetest.pos_to_string(newpos)..".name = '"..dump(nodename1).."' D"..minetest.pos_to_string({x=newpos.x,y=newpos.y+1,z=newpos.z})..".name = '"..dump(nodename2).."' ")
			until (nodename1=="air" and nodename2=="air") or newpos.y>=40
			minetest.chat_send_all(name.." renasceu em '"..minetest.pos_to_string(newpos).."'.")
			--print("[lunomods/on_command_respawnall.lua -- lunomods.on_respawnplayer(player='"..name.."')] posRespawn='"..dump(posRespawn).."', posRespawnAll='"..dump(posRespawnAll).."'")
			repeat
				player:setpos(newpos) --Favor nao por som antes do player ser instaciado no servidor
			until (player:getpos().x==newpos.x and player:getpos().z==newpos.z)
			--print("############################# "..name.." esta em '"..minetest.pos_to_string(player:getpos()).."'.")
			return true
		end
	else
		print("[lunomods/on_command_respawnall.lua -- lunomods.on_respawnplayer(player='???????')] Erro => Variavel 'player' nao foi declarada.")
	end
end

lunomods.set_respawnall = function(name) --name=nome do admin
	if name~=nil and name~="" then
		local player = minetest.get_player_by_name(name)
		if player ~= nil and player:is_player() then
			--[[
			local posRespawnAll = {
				x=math.ceil(player:getpos().x), --math.ceil(arredonda para cima de 0.5), math.floor(arredonda para menor de 0.5)
				y=math.ceil(player:getpos().y), 
				z=math.ceil(player:getpos().z) 
			} 
			]]--
			local posRespawnAll = player:getpos()
			lunomods.setGlobalValue("posRespawnAll", minetest.pos_to_string(posRespawnAll))
			minetest.chat_send_player(name, "Todos os jogadores renascerao em "..minetest.pos_to_string(posRespawnAll)..".", false)
			return true -- Handled chat message
		else
			print("erro => lunomods.gohome("..name..") --player de gohome invalido.")
		end
	else
		print("Erro => nao foi declarado o nome no lunomods.gohome('????????').")
	end
end

minetest.register_privilege("gohome", "O nogador pode tepeortar para sua casa.")

lunomods.gohome = function(name)
	if name~=nil and name~="" then
		local player = minetest.get_player_by_name(name)
		if player ~= nil and player:is_player() then
			if minetest.check_player_privs(name, {gohome=true}) then
				local pos = player:getpos()

				local consumir = "lunorecipes:magicdust"
				local posRespawn = lunomods.getCharValue(name, "posRespawn")
				local posRespawnAll = lunomods.getGlobalValue("posRespawnAll")
				local toPos = nil
	
				local item = player:get_wielded_item()
				if not minetest.setting_getbool("gohome_eatdust") or minetest.get_modpath("lunorecipes")==nil or item:get_name() == consumir then
					if posRespawn~=nil and posRespawn~="" then
						toPos = minetest.string_to_pos(posRespawn)
					elseif posRespawnAll~=nil and posRespawnAll~="" then
						toPos = minetest.string_to_pos(posRespawnAll)
					end

					if pos~=nil and toPos~=nil then
						--minetest.sound_play("sfx_teleporte", {pos=pos, max_hear_distance = 10}) --toca som "sfx_teleporte".ogg a distancia de 10 blocos do usuario.
						player:setpos(toPos)
						--minetest.sound_play("sfx_teleporte", {pos=toPos, max_hear_distance = 10}) --toca som "sfx_teleporte".ogg a distancia de 10 blocos do usuario.
			
						if 
							minetest.setting_getbool("gohome_eatdust")
							and minetest.get_modpath("lunomobs")~=nil
							and not minetest.setting_getbool("creative_mode") 
							--and not minetest.check_player_privs(name, {server=true}) 
						then
							item:take_item()
							player:set_wielded_item(item)
						end
						--local inv=player:get_inventory()
						--inv=minetest.get_inventory({type="player",name=player:get_player_name()})
				  		--inv:remove_item("main",ItemStack(consumir))

						return true
					else
						print("erro => lunomods.gohome("..name..")")
					end
				else
					minetest.chat_send_player(name, "Voce precisa segurar um 'Po Encantado' para executar esse comando.")
					minetest.sound_play("sfx_falha", {object=player, max_hear_distance = 10}) --toca som "sfx_teleporte".ogg a distancia de 10 blocos do usuario.
				end
			else
				minetest.chat_send_player(name, "Voce nao possui o privilegio para este comando.")
				minetest.sound_play("sfx_falha", {object=player, max_hear_distance = 10}) --toca som "sfx_teleporte".ogg a distancia de 10 blocos do usuario.
			end
		else
			print("erro => lunomods.gohome("..name..") --player de gohome invalido.")
		end
	else
		print("Erro => nao foi declarado o nome no lunomods.gohome('????????').")
	end
end

--##############################################################################################################################

minetest.register_on_newplayer(function(player)
	--print("[lunomods/on_command_respawnall.lua >>>> minetest.register_on_newplayer("..player:get_player_name()..")]")
	lunomods.on_newplayer(player)
end)
minetest.register_on_respawnplayer(function(player)
	--print("[lunomods/on_command_respawnall.lua >>>> minetest.register_on_respawnplayer("..player:get_player_name()..")]")
	return lunomods.on_respawnplayer(player)
end)

minetest.register_chatcommand("respawnall", {
	params = "",
	description = "Grava local de renascimento de todos os jogadores do servidor.",
	privs = {server=true},
	func = function(name, param)
		lunomods.set_respawnall(name)
	end,
})

--##############################################################################################################################

minetest.register_chatcommand("gohome", {
	params = "",
	description = "Teletransporta o jogador para o seu ponto de respawn.",
	privs = {},
	func = function(name, param)
		lunomods.gohome(name)
	end,
})

minetest.register_chatcommand("return", {
	params = "",
	description = "Teletransporta o jogador para o seu ponto de respawn.",
	privs = {},
	func = function(name, param)
		lunomods.gohome(name)
	end,
})

--##############################################################################################################################

minetest.register_chatcommand("morrer", {
	params = "",
	description = "Faz o player se suicidar",
	privs = {},
	func = function(name, param)
		--lunomods.gohome(name)
		local player = minetest.get_player_by_name(name)
		player:set_hp(0)
	end,
})

minetest.register_chatcommand("suicidar", {
	params = "",
	description = "Faz o player se suicidar",
	privs = {},
	func = function(name, param)
		--lunomods.gohome(name)
		local player = minetest.get_player_by_name(name)
		player:set_hp(0)
	end,
})

minetest.register_chatcommand("killme", {
	params = "",
	description = "Faz o player se suicidar",
	privs = {},
	func = function(name, param)
		--lunomods.gohome(name)
		local player = minetest.get_player_by_name(name)
		player:set_hp(0)
	end,
})

minetest.register_chatcommand("harakiri", {
	params = "",
	description = "Faz o player se suicidar",
	privs = {},
	func = function(name, param)
		--lunomods.gohome(name)
		local player = minetest.get_player_by_name(name)
		player:set_hp(0)
	end,
})

minetest.register_chatcommand("seppuku", {
	params = "",
	description = "Faz o player se suicidar",
	privs = {},
	func = function(name, param)
		--lunomods.gohome(name)
		local player = minetest.get_player_by_name(name)
		player:set_hp(0)
	end,
})
